package com.pen.interfece.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class FileUtils {

    @Value("${file.upload-dir}") // 从 application.properties 注入配置
    private String uploadRootDir;

    public String saveImage(MultipartFile file) throws IOException {
        // 1. 构建完整上传路径（例如：E:/uploads/images）
        String imageDir = uploadRootDir + File.separator + "images";
        File uploadPath = new File(imageDir);

        // 2. 创建目录（如果不存在）
        if (!uploadPath.exists()) {
            boolean dirsCreated = uploadPath.mkdirs();
            if (!dirsCreated) {
                throw new IOException("无法创建目录: " + uploadPath.getAbsolutePath());
            }
        }

        // 3. 生成唯一文件名（处理无后缀或空文件名）
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        String uniqueFileName = UUID.randomUUID() + fileExtension;

        // 4. 保存文件到目标路径
        File targetFile = new File(uploadPath.getAbsolutePath() + File.separator + uniqueFileName);
        file.transferTo(targetFile);

        // 5. 返回可直接访问的 URL 路径（如：/images/xxx.jpg）
        return "/images/" + uniqueFileName;
    }

    // 安全获取文件后缀（处理空文件名或无后缀情况）
    private String getFileExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return ".jpg"; // 默认后缀
        }
        int lastDotIndex = filename.lastIndexOf(".");
        return (lastDotIndex == -1) ? ".jpg" : filename.substring(lastDotIndex);
    }
}